package main.java.dao;

import com.mysql.cj.api.jdbc.JdbcConnection;
import main.java.entity.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    private String dirverName="com.mysql.jdbc.Driver";
    private String url ="jdbc:mysql://localhost:3306/test_sjj?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
    private String username="root";
    private String password="admin";

    public List<User> getAll(){
        List<User> users = new ArrayList<>();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Connection connection = null;
        try {
            Class.forName(dirverName);
            connection = DriverManager.getConnection(url,username,password);
            String sql ="select * from tb_user";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setAddress(resultSet.getString("address"));
                users.add(user);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(resultSet!= null){
                    resultSet.close();
                }
                if(preparedStatement!=null){
                    preparedStatement.close();
                }
                if(connection!=null){
                    connection.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }



        return users;
    }

}
